package com.chhuang.utils.config;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
 * 
* @ClassName: PropertiesUtil 
* @Description: TODO 
* @author: 黄晨 
* @date: 2015-3-25
*
 */
public class PropertiesUtil {
	private PropertiesUtil(){}
	
	/**
	 * 根据文件名、键名获取值
	 * @param name
	 * @param key
	 * @return
	 */
	public static String getValue(String name,String key){
		//注意路径默认指向的是classpath的根目录
        Configuration config = null;
        try {
			config = new PropertiesConfiguration(name+".properties");
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		String value = config.getString(key);
		return value;
	}

	/**
	 * 根据文件名、键名获取值
	 * @param name
	 * @param key 
	 * @param def 默认值
	 * @return
	 */
	public static String getValue(String name, String key, String def){
		//注意路径默认指向的是classpath的根目录
        Configuration config = null;
        try {
			config = new PropertiesConfiguration(name+".properties");
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		String value = config.getString(key, def);
		return value;
	}
	
	/**
	 * 根据文件名、键名设置值
	 * @param name
	 * @param key
	 * @param value
	 */
	public static void setValue(String name,String key,String value){
		Configuration config = null;
		try {
			config = new PropertiesConfiguration(name+".properties");
			config.setProperty(key, value);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取文件路径
	 * @param fileName
	 * @return
	 */
	public static String getRealPath(String fileName){
		String path = PropertiesUtil.class.getClassLoader().getResource("").getPath();
		if(System.getProperty("os.name").toLowerCase().startsWith("windows") && path.startsWith("/")){
			path = path.substring(1, path.length());
		}
		return path+fileName;
	}
}
